<template>
  <view>
    <view class="statis-container">
      <!-- 导航栏 -->
      <u-navbar title="统计" @leftClick="back"></u-navbar>
      <!-- 个人信息 -->
      <view class="user-info card">
        <view class="user-info-left">
          <image v-if="user.img_url" class="user-photo" :src="user.img_url" mode=""></image>
          <view class="user-name-image" v-else>{{ user.worker_name }}</view>
          <view>
            <view class="user-name">{{ user.worker_name }}</view>
            <view class="user-viewrule">办公室<text @click="showAlert">(查看规则)</text></view>
          </view>
        </view>
        <view class="user-info-right">
          <up-subsection :list="subsection" :current="current" @change="subChange"></up-subsection>
        </view>
      </view>
      <!-- 统计 日 -->
      <attend-calendar v-show="current == 0" :monthData="monthData" :staffDate="staffDate" @dayChange="dayChange"
        @monthChange="getStatisData"></attend-calendar>

      <!-- 统计 周 -->
      <!--       <Weeklystatistics v-show="current == 1"></Weeklystatistics>-->
      <!-- 统计 月 -->
      <month-calendar v-if="current == 1" :monthStatis="monthStatis" @monthChange="getStatisData"></month-calendar>

      <!-- 当日详细信息 -->
      <view class="clock-info">
        <!-- 截至时间 -->
        <view class="clock-base">
          统计截至<text style="margin-left: 14rpx;color: #333;">{{ showTime }}</text>
        </view>
        <view v-show="current == 0" class="clock-base">考勤组: {{ classes_name }}</view>
        <!-- 时间轴 -->
        <view v-show="current == 0" class="time-line">
          <time-line v-if="stepList.length > 0" backgroundColor='#969799' :infoList='stepList'></time-line>
          <view style="margin-bottom: 50rpx;" v-else>
            <up-empty mode="history" text="当天没有打卡记录">
            </up-empty>
          </view>
          <view>
            <button type="primary" @click="toggleRecord">{{ show_record ? "收起记录" : "打卡记录" }}</button>
            <!-- 打卡记录列表 -->
            <view v-show="show_record" class="record-list">
              <view v-if="dayRecords.length > 0" class="record-container">
                <view class="record-title">打卡记录 ({{ selectedDate }})</view>
                <view v-for="(record, index) in dayRecords" :key="index" class="record-item">
                  <view class="record-time">{{ formatTime(record.clock_time) }}</view>
                  <view class="record-type">{{ record.clock_type == 1 ? '上班' : '下班' }}</view>
                  <view class="record-location">{{ record.location || '无位置信息' }}</view>
                </view>
              </view>
              <view v-else class="no-record">
                <text>暂无打卡记录</text>
              </view>
            </view>
          </view>
        </view>
      </view>
      <!-- 底部导航栏 -->
      <u-tabbar :value="tabbarIndex" :placeholder="true">
        <u-tabbar-item @click="toClock" text="打卡" icon="map"></u-tabbar-item>
        <u-tabbar-item text="统计" icon="file-text"></u-tabbar-item>
        <u-tabbar-item @click="settingSetUp" text="设置" icon="setting"></u-tabbar-item>
      </u-tabbar>
    </view>
    <!-- 增加底部高度防止内容展示不全 -->
    <view style="height: 150rpx;"></view>
  </view>
</template>

<script>
import clock from '@/apis/cloud/clock';
import AttendCalendar from '@/components/clock/attend-calendar.vue';
import MonthCalendar from '@/components/clock/month-calendar.vue';
import TimeLine from '@/components/clock/TimeLine.vue';
import Weeklystatistics from '@/components/clock/Weeklystatistics.vue';
import { useUserStore } from '@/pinia-store/user';
import dayjs from 'dayjs';
import { mapStores } from 'pinia';

export default {
  components: {
    AttendCalendar,
    MonthCalendar,
    TimeLine,
    Weeklystatistics
  },
  data () {
    return {
      show_record: false,
      current: 0,
      taday: null,
      classes_name: '',
      staffDate: '2025-01-01', // 入职日期
      selectedDate: null, // 选中的日期
      dayRecords: [], // 存储获取的打卡记录
      tadayData: {
        am_end_time: "",
        clock_status: 0,
        clock_type: 0,
        date: "",
        end_time: "",
        is_holiday: 0,
        sb_clock_time: "",
        sb_location: "",
        start_time: "",
        week: "",
        worker_name: "",
        xb_clock_time: "",
        xb_location: ""
      },
      tabbarIndex: 1,
      showTime: null,
      subsection: [
        {
          name: '日'
        },
        {
          name: '月'
        }
      ],
      user: {
        img_url: '',
        worker_name: '',
      },
      // 月数据
      monthData: [],
      // 当日数据 时间轴展示
      stepList: [],
      // 月统计
      monthStatis: {},
    };
  },
  mounted () {
    this.taday = dayjs().format('YYYY-MM-DD');
    this.selectedDate = this.taday; // 初始化选中日期为今天

    this.showTime = dayjs().format('YYYY-MM-DD HH:mm:ss');
    this.user = this.userStore.user ? this.userStore.user : {
      img_url: null,
      worker_name: '张三'
    };
    this.getStatisData(dayjs().format('YYYY-MM'));
  },
  computed: {
    ...mapStores(useUserStore)
  },
  methods: {
    toggleRecord () {
      this.show_record = !this.show_record;
      // 如果展开记录且当前没有数据，则获取数据
      if (this.show_record && this.dayRecords.length === 0) {
        this.getDayRecordData();
      }
    },
    // 日变化
    async dayChange (day) {
      this.tadayData = this.monthData[day.index];
      this.selectedDate = this.tadayData.date; // 更新选中的日期
      this.setTimeLineData();

      // 如果记录区域是展开状态，则自动获取数据
      if (this.show_record) {
        this.show_record = !this.show_record;
        await this.getDayRecordData();
      }
    },

    // 获取指定日期的打卡记录
    async getDayRecordData () {
      if (!this.selectedDate) return;

      try {
        const params = {
          worker_id: this.user.worker_id,
          date: this.selectedDate
        };

        const response = await clock.getDayRecord(params);

        if (response.status === 1) {
          this.dayRecords = response.data || [];
        } else {
          uni.showToast({
            title: "当日无考勤打卡记录",
            icon: "error",
          });
          this.dayRecords = [];
        }
      } catch (error) {
        console.error("获取打卡记录出错:", error);
        uni.showToast({
          title: "获取打卡记录出错",
          icon: "error",
        });
        this.dayRecords = [];
      } finally {
        uni.hideLoading();
      }
    },

    // 格式化时间显示
    formatTime (timeString) {
      if (!timeString) return '--:--';
      return dayjs(timeString).format('HH:mm:ss');
    },

    setTimeLineData () {
      this.stepList = [];
      let am = {};
      let pm = {};

      // const isPastDay = this.tadayData.date < this.taday; // 只判断今天之前的日期
      const isPastDay = dayjs(this.tadayData.date).isBefore(dayjs(this.taday), 'day');

      const isWeekendOrHoliday = this.tadayData.week === '周日' || this.tadayData.is_holiday === 1;

      // 上班打卡
      if (this.tadayData.sb_clock_time != '') {
        am.post = this.tadayData.sb_location;
        let clock_time = dayjs(this.tadayData.sb_clock_time).format('HH:mm:ss');
        am.date = `上班 ${clock_time}`;
        // 迟到处理
        if (clock_time > this.tadayData.start_time) {
          am.abnormity = `上班时间${this.tadayData.start_time},${this.getDiffTime(this.tadayData.start_time, clock_time, true)}`;
          am.status = 0;
          am.type = '上午';
          am.is_apply = 0;
        } else {
          am.status = 1;
        }
        am.verifyStatus = 1;
      } else if (isPastDay && !isWeekendOrHoliday) {
        // 缺卡（仅显示昨天及更早且非周末/节假日）
        am = {
          date: '上班 缺卡',
          type: '上午',
          status: -1,
          is_apply: 0,
          abnormity: '上班缺卡'
        }
      }

      // 下班打卡
      if (this.tadayData.xb_clock_time != '') {
        pm.post = this.tadayData.xb_location;
        let clock_time = dayjs(this.tadayData.xb_clock_time).format('HH:mm:ss');
        pm.date = `下班 ${clock_time}`;
        // 早退处理
        if (clock_time < this.tadayData.end_time) {
          pm.abnormity = `下班时间${this.tadayData.end_time},${this.getDiffTime(clock_time, this.tadayData.end_time, false)}`;
          pm.status = 0;
          pm.type = '下午';
          pm.is_apply = 0;
        } else {
          pm.status = 1;
        }
        pm.verifyStatus = 1;
      } else if (isPastDay && !isWeekendOrHoliday) {
        // 缺卡（仅显示昨天及更早且非周末/节假日）
        pm = {
          date: '下班 缺卡',
          type: '下午',
          status: -1,
          is_apply: 0,
          abnormity: '下班缺卡'
        }
      }

      // 审批单处理
      if (this.tadayData.is_apply == 1) {
        if (this.tadayData.opr_type == '上午') {
          am = {
            date: `上班 ${this.tadayData.start_time}`,
            is_apply: this.tadayData.is_apply,
            ftype: this.tadayData.ftype,
            remark: this.tadayData.remark,
            post: this.tadayData.sb_location,
            status: 1,
            type: '上午'
          }
        } else {
          pm = {
            date: `下班 ${this.tadayData.end_time}`,
            is_apply: this.tadayData.is_apply,
            ftype: this.tadayData.ftype,
            remark: this.tadayData.remark,
            post: this.tadayData.xb_location,
            status: 1,
            type: '下午'
          }
        }
      }

      if (Object.keys(am).length > 0) this.stepList.push(am);
      if (Object.keys(pm).length > 0) this.stepList.push(pm);
    },
    getDiffTime (s1, s2, type) {
      const date1 = dayjs(`2020-01-01 ${s1}`);
      const date2 = dayjs(`2020-01-01 ${s2}`);

      if (!date1.isValid() || !date2.isValid()) {
        return type ? '迟到时间格式错误' : '早退时间格式错误';
      }

      let diffMinutes = date2.diff(date1, 'minute');
      let hours = Math.floor(diffMinutes / 60);
      let minutes = diffMinutes % 60;

      if (type) {
        return `晚到${hours === 0 ? '' : `${hours}小时`}${minutes === 0 ? '' : `${minutes}分`}记为迟到`
      } else {
        return `提前${hours === 0 ? '' : `${hours}小时`}${minutes === 0 ? '' : `${minutes}分`}记为早退`
      }
    },
    // 获取考勤数据
    async getStatisData (date) {
      uni.showLoading({ title: '加载中...', mask: true });
      const params = {
        worker_id: this.user.worker_id,
        // worker_id: 463,
        yearMonth: date,
        depart_id: this.user.depart_id,
        // depart_id: 1
      }

      try {
        const userGroupMsg = await clock.getLongLat(params); // 获取用户打卡信息
        this.staffDate = userGroupMsg.data.staff_date;
        this.classes_name = userGroupMsg.data.classes_name;

        const monthMsg = await clock.getWorkerMonth(params); // 月度考勤记录
        const monthResult = monthMsg.data;

        const leaveMsg = await clock.getLeaveMonth(params); // 审批单记录
        const leaveResult = {};


        if (userGroupMsg.status !== 1 || monthMsg.status !== 1 || leaveMsg.status !== 1) {
          uni.showToast({
            title: "获取失败，请重试",
            icon: "error",
          });
          return;
        }

        leaveMsg.data.forEach(item => {
          leaveResult[item.biz_date] = item;
        });

        let gongshi = 0; //累计工时分钟
        let chuqinDays = 0; // 出勤天数
        this.monthStatis = {
          workTime: 0, // 工时/出勤天数=平均工时
          chuqin: 0, //出勤
          xiuxi: 0, //休息
          chidao: 0, //迟到
          zaotui: 0, //早退
          queka: 0, //缺卡
          kuanggong: 0, //旷工
          waiqin: 0, //外勤
          buka: 0, //补卡
        }

        // 应出勤天数
        // let chuqinDays = 0;
        // 当天
        // const taday = new Date().getDate();
        this.monthData = monthResult.map(item => {
          // // 周几
          // const day = new Date(item.date).getDay();
          // // 非当月
          // if(date != dayjs().format('YYYY-MM')) {
          // 	if(item.is_holiday != 1 && day != 0) chuqinDays++;
          // }else {
          // 	// 当月当天之前
          // 	if(item.is_holiday != 1 && day != 0 && new Date(item.date).getDate() < taday)  chuqinDays++;
          // }

          // 初始化审批状态 0
          item.is_apply = 0;

          // 是否当天之后
          if (item.date > this.taday) {
            item.is_after = 1;
            return item
          }

          // 周日处理
          // if (item.week == '周日') {
          //   // item.is_holiday = 1;
          //   this.monthStatis.xiuxi++;
          //   return item
          // }

          // // 休息
          // if (item.is_holiday == 1) {
          //   this.monthStatis.xiuxi++;
          //   return item
          // }


          // 周末或节假日
          if (item.week === '周日' || item.is_holiday === 1) {
            // 标记为休息，不算缺卡/迟到/早退，日历显示绿色
            item.clock_status = 1;
            this.monthStatis.xiuxi++;
            return item;
          }
          // 此条有审批记录
          if (leaveResult[item.date] && item.date == leaveResult[item.date].biz_date) {
            item.is_apply = 1;
            item.ftype = leaveResult[item.date].ftype;
            item.remark = leaveResult[item.date].remark;
            item.opr_type = leaveResult[item.date].opr_type;
            item.clock_status = 1;
            if (leaveResult[item.date].ftype == '补卡') this.monthStatis.buka++;
          }

          // 处理当日数据
          if (this.taday == item.date) {
            this.tadayData = item;
            this.setTimeLineData(item);
          }

          // 是否外勤
          if (item.clock_type == 3) waiqin++;

          // 是否矿工
          if (item.sb_clock_time == '' && item.xb_clock_time == '') {
            // 暂定有考勤审批单就设定正常
            if (item.is_apply != 1) {
              item.clock_status = 0;
              this.monthStatis.kuanggong++;
            } else {
              item.clock_status = 1;
            }
            return item
          }

          // 出勤都有打卡记录
          if (item.sb_clock_time != '' && item.xb_clock_time != '') {
            const sb = new Date(item.sb_clock_time).getTime();
            const xb = new Date(item.xb_clock_time).getTime();
            const diff = xb - sb;
            const minutes = Math.floor(diff / 1000 / 60);
            gongshi += minutes;
            chuqinDays++;
            this.monthStatis.chuqin++;
          };

          // 审批也算出勤
          if (item.is_apply == 1) {
            chuqinDays++;
          }

          // 上班打卡状态
          if (item.sb_clock_time == '') {
            if (item.is_apply != 1) {
              item.is_sb_status = 0;
              item.clock_status = 0;
              this.monthStatis.queka++;
            } else {
              item.clock_status = 1;
            }
          }
          if (dayjs(item.sb_clock_time).format('HH:mm:ss') > item.start_time) {
            if (item.is_apply != 1) {
              item.is_sb_status = 2;
              item.clock_status = 0;
              this.monthStatis.chidao++;
            } else {
              item.clock_status = 1;
            }
          } else {
            item.is_sb_status = 1;
            item.clock_status = 1;
          }

          // 下班打卡状态
          if (item.xb_clock_time == '') {
            if (item.is_apply != 1) {
              item.is_xb_status = 0;
              item.clock_status = 0;
              this.monthStatis.queka++;
            } else {
              item.clock_status = 1;
            }
          }
          if (dayjs(item.xb_clock_time).format('HH:mm:ss') < item.end_time) {
            if (item.is_apply != 1) {
              item.is_xb_status = 2;
              item.clock_status = 0;
              this.monthStatis.zaotui++;
            } else {
              item.clock_status = 1;
            }
          } else {
            item.is_xb_status = 1;
            item.clock_status = 1;
          }
          return item;
        });
        // this.monthStatis.workTime = (gongshi / 60).toFixed(1)
        this.monthStatis.workTime = chuqinDays > 0 ? (gongshi / 60 / chuqinDays).toFixed(1) : 0;

      } catch (error) {
        uni.showToast({
          title: "获取失败，请重试",
          icon: "error",
        });
      } finally {
        uni.hideLoading();
      }
    },
    subChange (event) {
      this.current = event;
      this.show_record = !this.show_record;
    },
    back () {
      uni.switchTab({
        url: '/pages/workspace/home/index',
        animationType: 'pop-in',
        animationDuration: 200
      })
      // uni.navigateBack();
    },
    toClock () {
      uni.navigateTo({
        url: '/pages/workspace/attendance/clockIn',
        animationType: 'none'
      })
    },
    // 考勤规则 跳转
    showAlert () {
      uni.navigateTo({
        url: '/components/AttcemanntComponent/ViewRules/index',
        animationType: 'none'
      });
    },
    settingSetUp () {
      uni.navigateTo({
        url: '/pages/workspace/attendance/setup',
        animationType: 'none'
      })
    }
  },
  onLoad () {

  }
}
</script>

<style lang="scss">
page {
  box-sizing: border-box;
  max-width: 100vw;
  background-color: #F3F4F5;
  overflow-y: auto;
  padding: 0 24rpx;

}

.statis-container {
  // #ifdef H5
  margin: 120rpx 0 0 0;
  // #endif

  // #ifdef APP-PLUS
  margin: 180rpx 0 0 0;
  // #endif

  background-color: #fff;
  border-radius: 8rpx;
}

.clock-info {
  padding: 0 30rpx;

  .clock-base {
    font-size: 28rpx;
    color: #7C7C7C;
    margin-bottom: 10rpx;
  }

  .time-line {
    margin-top: 34rpx;
  }
}

.user-info {
  display: flex;
  justify-content: space-between;
  padding: 32rpx 24rpx 32rpx 32rpx;
  border-bottom: 1px solid #E6E6E6;
}

.user-info-left {
  display: flex;

  .user-photo {
    width: 86rpx;
    height: 86rpx;
    border-radius: 8rpx;
  }

  .user-name-image {
    width: 86rpx;
    height: 86rpx;
    line-height: 86rpx;
    text-align: center;
    color: #fff;
    border-radius: 8rpx;
    background-color: #0195FF;
  }

  .user-name {
    margin-top: 8rpx;
    margin-left: 28rpx;
    font-size: 28rpx;
    color: #555;
  }

  .user-viewrule {
    margin-left: 28rpx;
    font-size: 24rpx;
    color: #aaa;
    margin-top: 10rpx;

    text {
      margin-left: 8rpx;
      color: #0195FF;
    }
  }
}

.user-info-right {
  display: flex;
  width: 200rpx;
  align-items: center;
}

/* 新增样式 - 打卡记录列表 */
.record-list {
  margin-top: 20rpx;
  border: 1px solid #eee;
  border-radius: 12rpx;
  padding: 20rpx;
  background-color: #f9f9f9;
}

.record-title {
  font-size: 28rpx;
  font-weight: bold;
  margin-bottom: 20rpx;
  color: #333;
  text-align: center;
}

.record-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 0;
  border-bottom: 1px solid #eee;

  &:last-child {
    border-bottom: none;
  }
}

.record-time {
  font-size: 28rpx;
  color: #333;
  font-weight: 500;
  flex: 2;
}

.record-type {
  font-size: 24rpx;
  color: #0195FF;
  flex: 1;
  text-align: center;
}

.record-location {
  font-size: 22rpx;
  color: #7C7C7C;
  flex: 2;
  text-align: right;
}

.no-record {
  text-align: center;
  padding: 40rpx;
  color: #999;
  font-size: 26rpx;
}
</style>
